﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SIMA.Core.Exceptions;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace SIMA.Core.Extension
{
    public static class ObjectExtension
    {
        public static T Clone<T>(this T source)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new NonClonableObjectException();
            }
            if(Object.ReferenceEquals(source,null))
            {
                return default(T);
            }
            IFormatter formater = new BinaryFormatter();
            Stream stream = new MemoryStream();
            using (stream)
            {
                formater.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formater.Deserialize(stream);
            }
        }
    }
}
